package com.swpu.apiclientsdk.api;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.swpu.apiclientsdk.model.User;
import com.swpu.apiclientsdk.utils.SignUtils;;
import lombok.Data;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Data
public class ApiClient {


    private static final String GATEWAY_HOST = "http://localhost:8090";
    private String accessKey;
    private String secretKey;

    public ApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }


    public  String getNameByGet(String name){
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result= HttpUtil.get(GATEWAY_HOST+"/api/name/", paramMap);
        System.out.println(result);
        return result;
    }

    public  String getNameByPost(@RequestParam String name){
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result= HttpUtil.get(GATEWAY_HOST+"/api/name/", paramMap);
        System.out.println(result);
        return result;
    }

    private  Map<String,String> getHeader(String body){
        Map<String,String> map = new HashMap<>();
        map.put("accessKey",accessKey);
        map.put("nonce", RandomUtil.randomNumbers(4));
        map.put("body",body);
        map.put("timestamp",String.valueOf(System.currentTimeMillis()/1000));
        map.put("sign", SignUtils.getSign(body,secretKey));
        return map;
    }

    public String getNameByPost(@RequestBody User user){
        String json = JSONUtil.toJsonStr(user);

        //hutool工具包的使用，发送post请求
        HttpResponse httpResponse = HttpRequest.post(GATEWAY_HOST+"/api/name/user")//请求方式、请求路径
                .addHeaders(getHeader(json))//请求头 及 里面的参数
                .body(json)//请求体 用户参数
                .execute();
        System.out.println(httpResponse.getStatus());
        return httpResponse.body();
    }
}
